package com.cmy;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

public class EasyMail {
    public static void main(String[] args) throws Exception {
        Properties properties = new Properties();
        properties.setProperty("mail.host","stmp.qq.com");//设置QQ邮箱服务器
        properties.setProperty("mail.transport.protocol","smtp");
        properties.setProperty("mail.smtp.auth","true");//需要验证用户名密码

        //QQ邮箱需要SSL加密,
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable","true");
        properties.put("mail.smtp.ssl.socketFactory",sf);

//使用JavaMail 发送邮件的5个步骤
        //1.创建定义整个应用程序所需的环境信息的Session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("2603135842@qq.com","cvhfpkpdyrufecic");
            }
        });
        //开启Session的debug模式,以查看程序发送邮件的运行状态
        session.setDebug(true);
        //2.通过session得到transport对象
        Transport ts = session.getTransport();
        //3.使用邮箱的用户名和授权码连上邮件服务器
        ts.connect("smtp.qq.com","2603135842@qq.com","cvhfpkpdyrufecic");
        //4.创建邮件
        //需要传递session
        MimeMessage message = new MimeMessage(session);

        //发件人
        message.setFrom(new InternetAddress("2603135842@qq.com"));
        //收件人
        message.setRecipient(Message.RecipientType.TO,new InternetAddress("995613143@qq.com"));
        //邮件主题
        message.setSubject("easy mail");
        //邮件内容
        message.setContent("<h1 style='color:red'>hello! I'm testing</h1>","text/html;charset=UTF-8");
        //5.发送邮件
        ts.sendMessage(message,message.getAllRecipients());
        System.out.println("发送成功");
        //关闭连接
        ts.close();
    }
}

    